package com.vf.admin.platform.controller;

import com.vf.admin.common.BaseController;
import com.vf.admin.common.Constants;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.platform.dto.UserDto;
import com.vf.admin.platform.dto.UserRoleDto;
import com.vf.admin.platform.entity.*;
import com.vf.admin.platform.service.OrganService;
import com.vf.admin.platform.service.RoleService;
import com.vf.admin.platform.service.UserRoleService;
import com.vf.admin.platform.service.UserService;
import com.vf.admin.utils.RecuUtils;
import com.vf.admin.utils.StringEx;
import com.vf.admin.platform.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 平台用户
 */
@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    UserService userService;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    RoleService roleService;
    @Autowired
    private OrganService organService;
    @Resource
    RedisUtil redisUtil;



    


    /**
     * 获取所有下级的组织结构
     * @return
     */
    @RequestMapping("/left")
    @ResponseBody
    public Result findList(){
        List<Organ> list = new ArrayList<Organ>();
        try {
//            String jessionid = request.getSession().getId();
//            boolean jessionExists = redisUtil.hasKey(jessionid);
//            if(!jessionExists){
//
//            }
//            User user = (User)redisUtil.get(jessionid);
            User user = (User)request.getSession(false).getAttribute(Constants.access_token);
            List<Organ>  orgListbf = organService.getOrgAllList();
            orgListbf = getOrgAll(orgListbf,new ArrayList(),user.getOrgid());
            list= new ArrayList<Organ>();
            for(Organ org : orgListbf){
                if(!list.contains(org)){
                    list.add(org);
                }
            }
            int maxId = 0;
            if(list!=null && list.size()>0){
                list = list.stream().sorted(Comparator.comparing(Organ::getSorts).reversed()).collect(Collectors.toList());
                Optional<Organ > organOption = list.stream().min(Comparator.comparingInt(Organ ::getId));
                Organ organ = organOption.get();
                maxId = organ.getId();
            }

            Map<String,Object> retMap = new HashMap<String,Object>();
            retMap.put("defaultId",maxId);
            retMap.put("list",list);
            return this.sucessJSON(retMap,"返回成功!");
        } catch (Exception e) {
            logger.error("查询组织机构列表异常", e);
            return this.errorJSON("操作异常，请联系管理员");
        }
    }

    /**
     * 获取部门下的所有用户
     * @param pageBean 分页对象
     * @param user  用户
     * @return
     */
    @RequestMapping("/list")
    public String list(SplitPageBean pageBean, User user){
        try {
            Map<String, Object> map = new HashMap<>();
            if (StringEx.isNullOrLing(user.getOrgid())) {
                return this.error("部门编号不能为空");
            }

            Map<String,Object> paraMap = new HashMap<String,Object>();
            List<Organ> organList = organService.findList(paraMap,null);
            Integer[] orgidArray = null;
            if(organList!=null && organList.size()>0){
                List<Organ> organDtoList = RecuUtils.getInstance().findOranList(organList,user.getOrgid(),true);
                List<Integer> organIdDtoList = RecuUtils.getInstance().findOranIdList(organDtoList,user.getOrgid(),true);
                orgidArray = new Integer[organIdDtoList.size()];
                for(int e=0;e<organIdDtoList.size();e++){
                    Integer id = organIdDtoList.get(e);
                    orgidArray[e] = id;
                }
            }

            paraMap.clear();
            paraMap.put("orgidIn",orgidArray);
            if(user!=null){
                paraMap.put("loginname",user.getLoginname());
                paraMap.put("name",user.getName());
                paraMap.put("states",user.getStates());
            }else{
                user = new User();
            }
            SplitPageBean splitPage = new SplitPageBean(pageBean.getPageIndex(),pageBean.getPageSize());
            List<User> list = userService.findList(paraMap,splitPage);
            //查询对应组织机构部门的详情
            Organ organ = organService.get(user.getOrgid());
            Map<Integer,String> shiFouStateMap = Constants.getShiFouStateMap();

            Map<String,Object> resultMap = new HashMap<String,Object>();
            request.setAttribute("user",user);
            request.setAttribute("list",list);
            request.setAttribute("organ",organ);
            request.setAttribute("shiFouStateMap",shiFouStateMap);
            request.setAttribute("splitPage",splitPage);
            return "/web/platform/user/list";
        }catch(Exception e){
            logger.error("根据部门编号查询用户列表异常",e);
            return this.error("操作异常，请联系管理员");
        }
    }

    /**
     * @param user
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public Result addOrUpdate(User user){
        try{
            if(StringEx.isNull(user.getLoginname())){
                return this.errorJSON("用户名不能为空");
            }
            if(StringEx.isNull(user.getPassword())){
                return this.errorJSON("密码不能为空");
            }
            if(StringEx.isNull(user.getName())){
                return this.errorJSON("真实姓名不能为空");
            }
            if(StringEx.isNull(user.getOrgid())){
                return this.errorJSON("部门id不能为空");
            }
            if(user.getId() == null || user.getId()<=0){
                user.setStates(user.getStates() == null ? Constants.shiFou_STATE_FOU : user.getStates());
                userService.save(user);
            }else{
                User userBf = userService.get(user.getId());
                userBf.setPassword(user.getPassword());
                userBf.setLoginname(user.getLoginname());
                userBf.setComments(user.getComments());
                userBf.setName(user.getName());
                userBf.setStates(user.getStates() == null ? Constants.shiFou_STATE_FOU : user.getStates());
                userBf.setSorts(user.getSorts());
                userBf.setCode(user.getCode());
                userService.save(userBf);
            }
            return this.sucessJSON("保存成功");
        }catch(Exception e){
            logger.error("保存用户信息异常",e);
            return this.errorJSON("操作异常，请联系管理员");
        }
    }

    /**
     * 获取单个用户的详情
     * @param id  菜单id
     * @return
     */
    @RequestMapping("/detail")
    public String detail(Integer id,Integer orgid){
        try{
            Result result = new Result();
            User user = new User();
            if(id!=null && id>0){
                user = userService.get(id);
            }else{
                user.setOrgid(orgid);
            }
            Organ organ = organService.get(orgid);
            if(organ == null){
                return this.error("组织机构不存在");
            }

            Map<Integer,String> shiFouStateMap = Constants.getShiFouStateMap();
            request.setAttribute("user",user);
            request.setAttribute("organ",organ);
            request.setAttribute("shiFouStateMap",shiFouStateMap);
            return this.sucess("/web/platform/user/edit");
        }catch(Exception e){
            logger.error("查询用户详情异常", e);
            return this.error("/web/platform/user/list");
        }
    }

    /**
     * 删除用户
     * @param idArray 用户id
     * @return
     */
    @RequestMapping("/del")
    @ResponseBody
    public Result del(String idArray){
        try{
            if(StringEx.isNull(idArray)){
                return this.errorJSON("用户编号不能为空!");
            }
            String[] userIdArray = idArray.split(",");
            if(userIdArray!=null && userIdArray.length>0){
                for(String id : userIdArray){
                    if(StringEx.isNull(id)){
                        continue;
                    }
                    User user = userService.get(Integer.valueOf(id));
                    if(user!=null &&  user.getIsroot()!=null && user.getIsroot().intValue() == 1){
                        //最高权限用户不允许删除
                        return this.errorJSON("最高权限用户不允许删除!");
                    }else{
                        userService.del(user.getId());
                    }
                }
            }
            return this.sucess();
        }catch (Exception e){
            logger.error("删除平台用户信息异常", e);
            return this.errorJSON("操作异常，请联系管理员");
        }
    }

    /**
     * 获取所有角色,为用户分配角色
     */
    @RequestMapping("/userRoleList")
    public String roleListByUserId(Integer userId){
        try{
            if(StringEx.isNullOrLing(userId)){
                return this.error("用户编号不能为空!");
            }

            User user = userService.get(userId);
            Map<String,Object> paraMap = new HashMap<String,Object>();
            List<Role> roleList = roleService.findList(paraMap,null);

            paraMap.clear();
            paraMap.put("userid",userId);
            List<UserRole> userRoleList = userRoleService.findList(paraMap);

            Map<Integer,Integer> userRoleMap = new HashMap<Integer,Integer>();
            if(userRoleList!=null && userRoleList.size()>0){
                for(UserRole userRole : userRoleList){
                    userRoleMap.put(userRole.getRoleid(),userRole.getUserid());
                }
            }

            for(Role role : roleList){
                if(userRoleMap.get(role.getId())!=null && userRoleMap.get(role.getId().intValue()).intValue() == userId.intValue()){
                    role.setLAY_CHECKED(true);
                }else{
                    role.setLAY_CHECKED(false);
                }
            }
            request.setAttribute("user",user);
            request.setAttribute("roleList",roleList);
            return this.sucess("/web/platform/user/role");
        }catch(Exception e){
            logger.error("查询用户拥有的所有角色时异常", e);
            return this.error("查询用户拥有的所有角色时异常");
        }
    }

    /**
     * 保存为用户分配角色
     * @param  user 用户
     * @return
     */
    @RequestMapping("/saveUserRole")
    @ResponseBody
    public Result saveUserRole(User user){
        try{
            Map<String,Object> map = new HashMap<>();
            if(user.getId()<=0){
                return this.errorJSON("用户编号不能为空");
            }
            User userBf = userService.get(user.getId());
            if(userBf == null || userBf.getId()<=0){
                return this.errorJSON("用户信息不存在");
            }
            List<String> roleList = Arrays.asList(user.getRoleArray().split(","));

            userRoleService.delByUserId(userBf.getId());//删除当前用户的所有角色
            userRoleService.save(userBf.getId(),roleList);
            return this.sucessJSON("保存成功");
        }catch(Exception e){
            logger.error("保存为用户分配角色异常", e);
            return this.errorJSON("操作异常，请联系管理员");
        }
    }

    /**
     * 获取当前登录用户的角色对应的菜单权限
     */
    @RequestMapping("/roleMenu")
    public String roleMenu(){
        try{
            List<Menu> menuList = new ArrayList<Menu>();

            User user = (User)request.getSession(false).getAttribute(Constants.access_token);
//            String token = request.getHeader(Constants.access_token);
//            Map<String, Object> resMap = new HashMap<String,Object>();
//            User user = (User)redisUtil.get(token);

            Map<String,Object> paramap = new HashMap<String,Object>();
            paramap.put("userid",user.getId());
            List<Menu> list = userRoleService.findMenuListByUserId(paramap);

            List<Menu> resultList = new ArrayList<Menu>();
            if(list!=null && list.size()>0){
                for(Menu menu : list){
                    Menu resultMenu = new Menu();
                    resultMenu.setId(menu.getId());
                    resultMenu.setPid(menu.getPid());
                    resultMenu.setTitle(menu.getTitle());
                    resultMenu.setIcon(menu.getIcon());
                    resultMenu.setJump(menu.getLinks());
                    resultList.add(resultMenu);
                }
                menuList = RecuUtils.getInstance().findLeftMenuList(resultList,1);
            }
            request.setAttribute("menuList",menuList);
            return this.sucess("/web/main");
        }catch(Exception e){
            logger.error("获取当前登录用户的角色对应的菜单权限",e);
            return this.error("获取信息失败，请联系管理员！");
        }
    }

    /**
     * 获取当前登录用户的信息
     */
    @RequestMapping("/info")
    @ResponseBody
    public Result user(){
        try{
            String token = request.getHeader(Constants.access_token);
            Map<String, Object> resMap = new HashMap<String,Object>();

            User user = (User)redisUtil.get(token);
            UserDto userDto = new UserDto();
            userDto.setLoginname(user.getLoginname());
            userDto.setName(user.getName());
            userDto.setRolename(user.getRolename());
            Map<String,Object> resultMap = new HashMap<String,Object>();
            resultMap.put("user",userDto);
            return this.sucess(resultMap);
        }catch(Exception e){
            logger.error("获取当前登录用户的信息 user() ",e);
            return this.errorJSON("获取信息失败，请联系管理员！");
        }
    }

    /**
     * 递归当前登陆用户的组织机构id下的所有组织机构id
     */
    private List<Organ> getOrgAll(List<Organ> orgList,List<Organ> organlistbf,int orgid){
        for(Iterator<Organ> it = orgList.iterator(); it.hasNext();){
            Organ organ = it.next();
            int orgpidbf = organ.getPid();
            int orgidbf = organ.getId();
            if(orgidbf==0){
                organlistbf.add(organ);
            }else if(orgidbf==orgid){
                organlistbf.add(organ);
            }else if(orgpidbf==orgid){
                organlistbf.add(organ);
                organlistbf = getOrgAll(orgList,organlistbf,orgidbf);
            }
        }
        return organlistbf;
    }

}
